# https://leetcode.cn/problems/convert-sorted-list-to-binary-search-tree/
# 109. 有序链表转换二叉搜索树
# 给定一个单链表的头节点  head ，其中的元素 按升序排序 ，将其转换为高度平衡的二叉搜索树。
# 本题中，一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差不超过 1。

# Definition for singly-linked list.
class ListNode(object):
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next


# Definition for a binary tree node.
class TreeNode(object):
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


class Solution(object):
    def sortedListToBST(self, head):
        """
        :type head: Optional[ListNode]
        :rtype: Optional[TreeNode]
        """

        values = []
        node = head
        while node is not None:
            values.append(node.val)
            node = node.next

        return self.sortedListToBSTValues(values)

    def sortedListToBSTValues(self, values):
        if len(values) == 0:
            return None
        if len(values) == 1:
            return TreeNode(val=values[0])
        if len(values) == 2:
            left = TreeNode(val=values[0])
            root = TreeNode(val=values[1])
            root.left = left
            return root

        mid = int(len(values) / 2)
        left_node = self.sortedListToBSTValues(values[0:mid])
        right_node = self.sortedListToBSTValues(values[mid + 1:len(values)])
        root_node = TreeNode(val=values[mid])
        root_node.left = left_node
        root_node.right = right_node
        return root_node
